import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export const useQueryAnalyticsStore = defineStore('queryAnalytics', () => {
  // 状态
  const loading = ref(false)
  const overview = ref({
    totalQueries: 0,
    averageTokens: 0,
    successRate: 0,
    averageResponseTime: 0,
    todayQueries: 0,
    weekQueriesGrowth: 0,
  })

  // 趋势数据
  const trends = ref({
    labels: [],
    queries: [],
    tokens: [],
    responseTime: [],
  })

  // 活跃用户数据
  const activeUsers = ref([])

  // 数据集分析
  const datasetAnalytics = ref({
    mostQueried: [],
    distribution: [],
    growthTrend: {
      labels: [],
      datasets: [],
    },
  })

  // 内容分析
  const contentAnalytics = ref({
    keywordCloud: [],
    lengthDistribution: [],
    errorAnalysis: [],
  })

  // 模型性能
  const modelPerformance = ref({
    responseTime: [],
    tokenConsumption: [],
    successRate: [],
  })

  // 时间维度
  const timeDimension = ref('day') // 'hour', 'day', 'week', 'month'

  // 获取概览数据
  const fetchOverview = async () => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/overview')
      overview.value = response.data
      return response.data
    } catch (error) {
      console.error('获取概览数据失败', error)
      ElMessage.error('获取概览数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取趋势数据
  const fetchTrends = async (dimension = timeDimension.value) => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/trends', {
        params: { dimension },
      })
      trends.value = response.data
      timeDimension.value = dimension
      return response.data
    } catch (error) {
      console.error('获取趋势数据失败', error)
      ElMessage.error('获取趋势数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户分析数据
  const fetchUserAnalytics = async (sortBy = 'queryCount') => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/users', {
        params: { sortBy },
      })
      activeUsers.value = response.data.activeUsers
      return response.data
    } catch (error) {
      console.error('获取用户分析数据失败', error)
      ElMessage.error('获取用户分析数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取数据集分析
  const fetchDatasetAnalytics = async () => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/datasets')
      datasetAnalytics.value = response.data
      return response.data
    } catch (error) {
      console.error('获取数据集分析失败', error)
      ElMessage.error('获取数据集分析失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取内容分析
  const fetchContentAnalytics = async () => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/content')
      contentAnalytics.value = response.data
      return response.data
    } catch (error) {
      console.error('获取内容分析失败', error)
      ElMessage.error('获取内容分析失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取模型性能分析
  const fetchModelPerformance = async () => {
    loading.value = true
    try {
      const response = await axios.get('/api/records/analytics/models')
      modelPerformance.value = response.data
      return response.data
    } catch (error) {
      console.error('获取模型性能分析失败', error)
      ElMessage.error('获取模型性能分析失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 自定义分析
  const fetchCustomAnalytics = async (params) => {
    loading.value = true
    try {
      const response = await axios.post('/api/records/analytics/custom', params)
      return response.data
    } catch (error) {
      console.error('获取自定义分析失败', error)
      ElMessage.error('获取自定义分析失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 计算属性
  const growthRate = computed(() => {
    if (!overview.value.weekQueriesGrowth) return 0
    return overview.value.weekQueriesGrowth
  })

  const successRateColor = computed(() => {
    const rate = overview.value.successRate
    if (rate >= 90) return '#67C23A' // 成功
    if (rate >= 75) return '#E6A23C' // 警告
    return '#F56C6C' // 危险
  })

  // 转换为图表数据的方法
  const trendDataForChart = computed(() => {
    return {
      labels: trends.value.labels,
      datasets: [
        {
          label: '查询数',
          data: trends.value.queries,
          borderColor: '#409EFF',
          backgroundColor: 'rgba(64, 158, 255, 0.2)',
        },
        {
          label: 'Token消耗',
          data: trends.value.tokens,
          borderColor: '#67C23A',
          backgroundColor: 'rgba(103, 194, 58, 0.2)',
        },
        {
          label: '响应时间(ms)',
          data: trends.value.responseTime,
          borderColor: '#E6A23C',
          backgroundColor: 'rgba(230, 162, 60, 0.2)',
        },
      ],
    }
  })

  const datasetDistributionForChart = computed(() => {
    return {
      labels: datasetAnalytics.value.distribution.map((item) => item.name),
      datasets: [
        {
          data: datasetAnalytics.value.distribution.map((item) => item.count),
          backgroundColor: [
            '#409EFF',
            '#67C23A',
            '#E6A23C',
            '#F56C6C',
            '#909399',
            '#6b778c',
            '#b643cd',
            '#42CCA9',
          ],
        },
      ],
    }
  })

  // 重置状态
  const reset = () => {
    overview.value = {
      totalQueries: 0,
      averageTokens: 0,
      successRate: 0,
      averageResponseTime: 0,
      todayQueries: 0,
      weekQueriesGrowth: 0,
    }
    trends.value = {
      labels: [],
      queries: [],
      tokens: [],
      responseTime: [],
    }
    activeUsers.value = []
    datasetAnalytics.value = {
      mostQueried: [],
      distribution: [],
      growthTrend: {
        labels: [],
        datasets: [],
      },
    }
    contentAnalytics.value = {
      keywordCloud: [],
      lengthDistribution: [],
      errorAnalysis: [],
    }
    modelPerformance.value = {
      responseTime: [],
      tokenConsumption: [],
      successRate: [],
    }
  }

  return {
    // 状态
    loading,
    overview,
    trends,
    activeUsers,
    datasetAnalytics,
    contentAnalytics,
    modelPerformance,
    timeDimension,

    // 计算属性
    growthRate,
    successRateColor,
    trendDataForChart,
    datasetDistributionForChart,

    // 方法
    fetchOverview,
    fetchTrends,
    fetchUserAnalytics,
    fetchDatasetAnalytics,
    fetchContentAnalytics,
    fetchModelPerformance,
    fetchCustomAnalytics,
    reset,
  }
})
